<template>
  <a-form-model
    ref="formComp"
    :model="formData"
    :rules="rules"
    layout="horizontal"
    class="AsteriskAfter newEditStyle">
    <full-parent-dom-with-dask :loading="spinningLoading"></full-parent-dom-with-dask>
    <a-row v-if="showPolicyName">
      <a-col :md="24" :sm="24">
        <a-form-model-item :label="$t('policyName')" class="customFormModelItem" prop="name">
          <a-input v-model.trim="formData.name" :disabled="isReadonly" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <!-- 通用前置条件 -->
    <a-row v-if="hasTitle">
      <a-col :md="24" :sm="24">
        <a-form-model-item :label="$t('tyqztj')" class="customFormModelItem">
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="40">
      <!-- SOC电量(%) -->
      <a-col :md="8" :sm="24">
        <a-form-model-item prop="lowestSoc">
          <template #label>
            <span>{{ $t('socdl') }}</span>
            <question-mark-tip :tip-title="$t('socdlTip')" :popupContainer="getPopupContainer">
            </question-mark-tip>
          </template>
          <a-input
            v-model="formDataItems.lowestSoc"
            style="width:100%"
            :disabled="isReadonly"
              />
        </a-form-model-item>
      </a-col>
      <!-- 蓄电池电压 -->
      <a-col :md="8" :sm="24">
        <a-form-model-item
          prop="lowestVoltage"
        >
          <template #label>
            <span>{{ $t('xdcdy') }}</span>
            <question-mark-tip :tip-title="$t('xdcdyTip')" :popupContainer="getPopupContainer">
            </question-mark-tip>
          </template>
          <a-input
            v-model="formDataItems.lowestVoltage"
            style="width:100%"
            :disabled="isReadonly"
              />
        </a-form-model-item>
      </a-col>
      <!-- 倒计时时长(min) -->
      <a-col :md="8" :sm="24">
        <a-form-model-item
          prop="countDown"
        >
          <template #label>
            <span>{{ $t('djssc') }}</span>
            <question-mark-tip :tip-title="$t('djsscTip')" :popupContainer="getPopupContainer">
            </question-mark-tip>
          </template>
          <a-input v-model="formDataItems.countDown" style="width:100%" :disabled="isReadonly" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row class="mt12" :gutter="40">
      <!-- 可升级温度(℃) -->
      <a-col :md="8" :sm="24">
        <a-form-model-item
          prop="temperature">
          <template #label>
            <span>{{ $t('ksjcwd') }}</span>
            <question-mark-tip :tip-title="$t('ksjcwdTip')" :popupContainer="getPopupContainer">
            </question-mark-tip>
          </template>
          <a-input
            v-model="formDataItems.temperature"
            style="width:100%"
            :disabled="isReadonly"
              />
        </a-form-model-item>
      </a-col>
      <!-- 下载失败次数 -->
      <a-col :md="8" :sm="24">
        <a-form-model-item
          prop="failureNumber">
          <template #label>
            <span>{{ $t('xzsbcs') }}</span>
            <question-mark-tip :tip-title="$t('xzsbcsTip')" :popupContainer="getPopupContainer">
            </question-mark-tip>
          </template>
          <a-input
            v-model="formDataItems.failureNumber"
            style="width:100%"
            :disabled="isReadonly" />
        </a-form-model-item>
      </a-col>
      <!-- 升级失败次数 -->
      <a-col :md="8" :sm="24">
        <a-form-model-item
          :colon="false"
          prop="upgradeFailureNumber">
          <template #label>
            <span>{{ $t('sjsbcs') }}</span>
            <question-mark-tip :tip-title="$t('sjsbcsTip')" :popupContainer="getPopupContainer">
            </question-mark-tip>
          </template>
          <a-input
            v-model="formDataItems.upgradeFailureNumber"
            style="width:100%"
            :disabled="isReadonly" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <!-- 烧写设置 -->
<!--    <a-row>-->
<!--      <a-col :md="24" :sm="24">-->
<!--        <a-form-model-item :label="$t('sxSetting')" class="customFormModelItem" prop>-->
<!--          <a-row :gutter="40">-->
<!--            &lt;!&ndash; 是否自由烧写 &ndash;&gt;-->
<!--            <a-col :md="12" :sm="24">-->
<!--              <a-row>-->
<!--                <a-col :md="8" :sm="24">-->
<!--                  <a-form-model-item>-->
<!--                    {{ $t('sfzysx') }}-->
<!--                  </a-form-model-item>-->
<!--                </a-col>-->
<!--                <a-col :md="16" :sm="24">-->
<!--                  <a-form-model-item>-->
<!--                    <yes-and-no-select-->
<!--                      :default-value="formDataItems.isFreeBurning"-->
<!--                      :disabled="isReadonly"-->
<!--                      @changeoption="changeSxSetting">-->
<!--                    </yes-and-no-select>-->
<!--                  </a-form-model-item>-->
<!--                </a-col>-->
<!--              </a-row>-->
<!--            </a-col>-->
<!--            &lt;!&ndash; 自由烧写次数 &ndash;&gt;-->
<!--            <a-col :md="12" :sm="24">-->
<!--              <a-row>-->
<!--                <a-col :md="8" :sm="24">-->
<!--                  <a-form-model-item>-->
<!--                    {{ $t('zysxCount') }}-->
<!--                  </a-form-model-item>-->
<!--                </a-col>-->
<!--                <a-col :md="16" :sm="24">-->
<!--                  <a-form-model-item-->
<!--                    :colon="false"-->
<!--                    class="customFormModelItem"-->
<!--                    prop="freeBurningTime"-->
<!--                  >-->
<!--                    <a-input-number-->
<!--                      :min="1"-->
<!--                      v-model="formDataItems.freeBurningTime"-->
<!--                      :disabled="isReadonly || !(formDataItems.isFreeBurning * 1)"-->
<!--                      style="width:100%" />-->
<!--                  </a-form-model-item>-->
<!--                </a-col>-->
<!--              </a-row>-->
<!--            </a-col>-->
<!--          </a-row>-->
<!--        </a-form-model-item>-->
<!--      </a-col>-->
<!--    </a-row>-->
  </a-form-model>
</template>
<script>
import FullParentDomWithDask from '@/components/LoadDataSpin/FullParentDomWithDask.vue'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import YesAndNoSelect from '@/views/components/YesAndNoSelect'
import { strategyInitFormData, strategyInitFormItems,qualityReviewInitFormItems } from '../config/form'
import lodash from 'lodash'
import { checkTextLen } from '@/utils/validate'
export default {
  components: {
    FullParentDomWithDask,
    QuestionMarkTip,
    YesAndNoSelect
  },
  props: {
    showPolicyName:{
      type: Boolean,
      default: true
    },
    isReadonly: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ''
    },
    time: {
      type: Number,
      default: 78140
    },
    isCopy: {
      type: Boolean,
      default: false
    },
    versionType: {
      type: String,
      default: ''
    },
    upgradeTriggerType: {
      type: String,
      default: ''
    },
    hasTitle: {
      type: Boolean,
      default: true
    },
  },
  data () {
    const _this = this
    const checkNumber = (min1, max, text, callback, required = false) => {
      if (!required && !text && text !== 0) {
        callback()
        return
      }
      const val = text * 1
      const msg = _this.$t('rangeIntegerErrorTip').replace('X~Y', min1 + '-' + max)
      if (val < min1 || val > max) {
        callback(new Error(msg))
        return
      }
      if (!(/^[-]?\d+$/.test(text + ''))) {
        callback(new Error(msg))
        return
      }
      if ((/^[-]?0+\d+$/.test(text + ''))) {
        callback(new Error(msg))
        return
      }
      if ((/^[-]0+/.test(text + ''))) {
        callback(new Error(msg))
        return
      }
      callback()
    }
    const checkRequiredItem = (rule, text, callback) => {
      (!_this.formDataItems[rule.field] && _this.formDataItems[rule.field] !== 0) ? callback(new Error(rule.message)) : callback()
    };
    return {
      formData: lodash.cloneDeep(strategyInitFormData),
      // formDataItems: lodash.cloneDeep(strategyInitFormItems),
      formDataItems:null,
      spinningLoading: false,
      rules: {
        name: [
          { required: true, message: this.$t('pleaseInput') },
          { validator: checkTextLen() }
        ],
        lowestSoc: [
          { required: true, message: this.$t('请输入1-99的整数'), validator: checkRequiredItem },{
          validator: (rule, text, callback) => {
            checkNumber(1, 99, _this.formDataItems.lowestSoc, callback)
          }
        }],
        lowestVoltage: [
          { required: true, message: this.$t('请输入1-240的整数'), validator: checkRequiredItem },{
          validator: (rule, text, callback) => {
            checkNumber(1, 240, _this.formDataItems.lowestVoltage, callback)
          }
        }],
        countDown: [
          { required: true, message: this.$t('请输入1-60的整数'), validator: checkRequiredItem },{
          validator: (rule, text, callback) => {
            checkNumber(1, 60, _this.formDataItems.countDown, callback)
          }
        }],
        failureNumber: [
          { required: true, message: this.$t('请输入1-30的整数'), validator: checkRequiredItem },{
          validator: (rule, text, callback) => {
            checkNumber(1, 30, _this.formDataItems.failureNumber, callback)
          }
        }],
        temperature: [
          { required: true, message: this.$t('请输入-100-100的整数'), validator: checkRequiredItem },{
          validator: (rule, text, callback) => {
            checkNumber(-100, 100, _this.formDataItems.temperature, callback)
          }
        }],
        freeBurningTime: [
          { required: true, message: this.$t('请输入1-100的整数'), validator: checkRequiredItem },{
          validator: (rule, text, callback) => {
            checkNumber(1, 100, _this.formDataItems.freeBurningTime, callback)
          }
        }],
        upgradeFailureNumber: [
          { required: true, message: this.$t('请输入1-999的整数'), validator: checkRequiredItem },
          {
            validator: (rule, text, callback) => {
              checkNumber(1, 999, _this.formDataItems.upgradeFailureNumber, callback, true)
            }
          }]
      }
    }
  },
  created() {
    this.resetFormData(!this.id || this.isCopy)
  },
  mounted(){
    if(this.showPolicyName){
      this.formDataItems=lodash.cloneDeep(strategyInitFormItems)
    }else{
      this.formDataItems=lodash.cloneDeep(qualityReviewInitFormItems)
    }
  },
  watch: {
    time: {
      handler () {
        // this.resetFormData(!this.id || this.isCopy)
        if (this.id) {
          this.getDetailData()
        }
      },
      immediate: true
    },
  },
  methods: {
    // 获取详情数据
    getDetailData () {
      this.spinningLoading = true
      this.$store.dispatch('getStrategyDetailData', {id : this.id,versionType:this.versionType, upgradeTriggerType:this.upgradeTriggerType}).then(res => {
        const data = res.data
        if (data) {
          this.formData.id = this.isCopy ? '' : this.id
          if (this.formData.id) {
            this.formData.name = data.name
          }
          this.formData.type = 2
          this.setFormDataItems(data.items)
        }
      }).finally(() => {
        this.spinningLoading = false
      })
    },
    // 编辑时设置已配置的选项
    setFormDataItems (items) {
      const obj = {}
      items.forEach(item => {
        obj[item.code] = item.value
      })
      this.formDataItems = obj
    },
    resetFormData (isSetName = true) {
      this.$refs.formComp && this.$refs.formComp.resetFields()
      this.formData = lodash.cloneDeep(strategyInitFormData)
      if (isSetName) {
        this.setDefaultName()
      }
      this.formDataItems = lodash.cloneDeep(strategyInitFormItems)
    },
    setDefaultName () {
      const name = this.$t('tjcl')
      this.formData.name = `${name}[${this.$commonFun.getDateMinuteStr(new Date())}]`
    },
    // 获取表单中的数据
    getFormData () {
      return new Promise((resolve, reject) => {
        this.$refs.formComp.validate(valid => {
          if (!valid) {
            reject(valid)
            return
          }
          if (!this.otherCheck()) {
            reject(new Error('未选择软件'))
            return
          }
          const formData = lodash.clone(this.formData)
          const formDataItems = []

          // eslint-disable-next-line no-restricted-syntax
          for (const k in this.formDataItems) {
            let value = this.formDataItems[k]
            if (value === null) {
              value = ''
            } else if (typeof value !== 'number') {
              value += ''
            }
            formDataItems.push({
              code: k,
              value
            })
          }
          formData.items = formDataItems
          formData.type = 2
          formData.versionType = this.versionType;
          formData.upgradeTriggerType = this.upgradeTriggerType;
          resolve(formData)
        })
      })
    },
    toQualityFormData(){
      const formData={
        items:{}
      }
      this.$refs.formComp.validate(valid => {
        if (!valid) {
          return
        }
        const formDataItems = []
        // eslint-disable-next-line no-restricted-syntax
        for (const k in this.formDataItems) {
          let value = this.formDataItems[k]
          if (value === null) {
            value = ''
          } else if (typeof value !== 'number') {
            value += ''
          }
          formDataItems.push({
            code: k,
            value
          })
        }
        formData.items = formDataItems
        })
        return formData
      },
    otherCheck () {
      return true
    },
    getPopupContainer () {
      return this.$refs.formComp.$el
    },
    changeSxSetting (val) {
      this.formDataItems.isFreeBurning = val
      if (val === '0') {
        this.formDataItems.freeBurningTime = ''
        this.$nextTick(() => {
          this.$refs.formComp.validateField('freeBurningTime')
        })
      }
    }
  }
}
</script>
<style scoped lang="less">
.editConditionStrategyFormComp {
  overflow: auto;
  position: relative;
}
</style>
